//
//  ThemeTask.swift
//  HiWidget
//
//  Created by dn56-macbook on 2024/9/26.
//

import UIKit
struct ThemeDiyConfig: Codable{
    var configs: String? =  ""
    var app_configs: String? = ""
    var lock_configs: String? = ""
    var widget_configs: String? = ""
}
struct ThemeDiyApp: Codable{
    var name: String? = ""
    var url: String? = ""
}
struct ThemeDiyInfo: Codable{
    var count: Int?       = 0
    var pageCount: Int?   = 0
    var list: [ThemeDiy]? = []
    var baseUrl: String?  = ""
}
struct ThemeDiy: Codable{
    var tid: Int? = 0
    var tid_theme: Int? = 0//一般下和tid 相同 但是如果用户微分享 tid没有值tid_theme有值
    var previews: [String]? = []//背景图
    var img: String? = ""//预览图
    var name: String? = ""
    var share_code: String? = ""
    var up_time: Double? = 0
    var state: Int? = -1 // -1未分享 0禁用 1正常
    var baseUrl: String? = ""
    
    var lock_data: Data? = nil
    var panel_data: Data? = nil
}
struct ThemeDiyFile: Codable{
    var url: [String]? = []
    var baseUrl: String? = ""
}
struct ThemeDiyTask{
    ///获取卓达列表
    func themeUserDiyList(_ page: Int,sucesss: @escaping ((_ info :ThemeDiyInfo) -> ()),
                                      failure: @escaping ((_ error  :String) -> ())){
        let host = BaseParam.appParam()
        var parames: [String: String] = [:]
        if let uid = userId{
            parames.updateValue("\(uid)", forKey: "uid")
        }
        parames.updateValue("\(page)", forKey: "page")
        BaseTask.request(path: "theme/user-diy-list", parames: parames, host: host) { model, json in
            if let datacontent = json["data"] as? String,let data = datacontent.deCryptData(algorithm: .DES, keyData: host.decode_key){
                guard let info = try? JSONDecoder().decode(ThemeDiyInfo.self, from: data) else { return failure(model.msg) }
                sucesss(info)
            }else{
                failure(model.msg)
            }
            debugPrint("json",json)
        } failure: { error in
            failure(error)
        }
    }
    ///删除桌搭
    func themeUserDiyDelete(_ tid: Int,
                            sucesss: @escaping ((_ finish :Bool) -> ()),
                            failure: @escaping ((_ error  :String) -> ())){
        let host = BaseParam.appParam()
        var parames: [String: String] = [:]
        if let uid = userId{
            parames.updateValue("\(uid)", forKey: "uid")
        }
        parames.updateValue("\(tid)", forKey: "tid")
        BaseTask.request(path: "theme/del-user-diy", parames: parames, host: host) { model, json in
            if model.success(){
                sucesss(true)
            }else{
                failure(model.msg)
            }
        } failure: { error in
            failure(error)
        }

    }
    ///文件上传
    func themeFileUpload(_ listData: [[String: Data]],
                           sucesss: @escaping ((_ info :ThemeDiyFile) -> ()),
                            failure: @escaping ((_ error  :String) -> ())){
        let host = BaseParam.appParam()
        var parames: [String: String] = [:]
        if let uid = userId{
            parames.updateValue("\(uid)", forKey: "uid")
        }
        BaseTask.uploadFileDatas(path: "theme/post-user-resource", parames: parames, imageDatas: listData, host: host) { model, json in
            if let info = json["data"] as? String,let data = info.deCryptData(algorithm: .DES, keyData: host.decode_key){
                guard let info = try? JSONDecoder().decode(ThemeDiyFile.self, from: data) else { return failure(model.msg) }
                sucesss(info)
            }else{
                failure(model.msg)
            }
        } failure: { error in
            failure(error)
        }
    }
    func themeUserDiyPost(_ name: String,
                          tid: Int? = nil,
                          widgets: [String],
                          lockscreen_widgets: [String],
                          previews_url: [String],
                          img_url: [String],
                          appids: [String] = [],
                          icons: [String] = [],
                          layout_configs: String,
                          app_configs: String,
                          lock_configs: String,
                          widget_configs: String,
                          sucesss: @escaping ((_ info :ThemeDiy) -> ()),
                          failure: @escaping ((_ error  :String) -> ())){
        let host = BaseParam.appParam()
        var parames: [String: String] = [:]
        if let uid = userId{
            parames.updateValue("\(uid)", forKey: "uid")
        }
        if let tid,tid > 0{
            parames.updateValue("\(tid)", forKey: "tid")
        }
        parames.updateValue(name, forKey: "name")
        parames.updateValue(widgets.joined(separator: ","), forKey: "widgets")//组件，多个逗号隔开
        parames.updateValue(lockscreen_widgets.joined(separator: ","), forKey: "lockscreen_widgets")//锁屏组件，多个逗号隔开
        parames.updateValue("", forKey: "wp_switch")
        parames.updateValue("", forKey: "super_widgets")//超级组件id，多个逗号隔开
        parames.updateValue("", forKey: "dynamic_island")//动画岛，多个逗号隔开
        parames.updateValue("", forKey: "wallpaper_diy")//壁纸制作，多个逗号隔开
        parames.updateValue(previews_url.joined(separator: ","), forKey: "previews_url")//展示图片，多个逗号隔开
        parames.updateValue(img_url.joined(separator: ","), forKey: "img_url")//缩略图
        parames.updateValue(layout_configs, forKey: "configs")//通用
        parames.updateValue(app_configs, forKey: "app_configs")//app
        parames.updateValue(lock_configs, forKey: "lock_configs")//锁屏
        parames.updateValue(widget_configs, forKey: "widget_configs")//锁屏

        BaseTask.uploadFile(path: "theme/post-user-diy", parames: parames, imgData: nil, host: host) { model, json in
            if let info = json["data"] as? String,let data = info.deCryptData(algorithm: .DES, keyData: host.decode_key){
                guard let info = try? JSONDecoder().decode(ThemeDiy.self, from: data) else { return failure(model.msg) }
                sucesss(info)
            }else{
                failure(model.msg)
            }
        } failure: { error in
            failure("error")
        }

    }
    //MARK: 本接口用于 获取模版的基本数据
    func themeDiyConfig(_ tid: Int,sucesss: @escaping ((_ info :ThemeDiyConfig) -> ()),failure: @escaping ((_ error  :String) -> ())){
        let host = BaseParam.appParam()
        var parames: [String: String] = [:]
        if let uid = userId{
            parames.updateValue("\(uid)", forKey: "uid")
        }
        parames.updateValue("\(tid)", forKey: "tid")
        BaseTask.request(path: "theme/diy-layout", parames: parames, host: host) { model, json in
            if let datacontent = json["data"] as? String,let data = datacontent.deCryptData(algorithm: .DES, keyData: host.decode_key){
                guard let info = try? JSONDecoder().decode(ThemeDiyConfig.self, from: data) else { return failure(model.msg) }
                sucesss(info)
                if let lockConfig = info.configs,let data = lockConfig.data(using: .utf8){
                    if let lockInfo = try? JSONDecoder().decode(ThemeDiyBindModel.self, from: data){
                        
                    }
                }
                if let app_configs = info.app_configs,let data = app_configs.data(using: .utf8){
                    if let list = try? JSONDecoder().decode([ThemeDiyApp].self, from: data){
                        
                    }
                }
                if let widget_configs = info.widget_configs,let data = widget_configs.data(using: .utf8){
                    let list = task.paneDataToPanelModel(data)
                }
                
            }else{
                
                failure(model.msg)
            }
        } failure: { error in
            failure(error)
        }

    }
    let task = ThemeDiyManage()
    func uploadFile(_ list: [String],
                      sucesss: @escaping ((_ list: [String]) -> ()),
                      failure: @escaping ((_ error: String) -> ())){
        
        uploadFileTask(list, sucesss: { map in
            var listData: [String] = []
            list.forEach { item in
                if let url = map[item]{
                    listData.append(url)
                }
            }
            sucesss(listData)
        }, failure: failure)
    }
    
    private func uploadFileTask(_ list: [String],
                        sucesss: @escaping ((_ map: [String: String]) -> ()),
                       failure: @escaping ((_ error:String) -> ())){
        
        var listFileName: [String] = list
        let listURL: [String :String] = task.getListFile(list)
        listURL.forEach { objc in
            listFileName.removeAll { name in
                return objc.key == name
            }
        }
        
        var listData: [[String: Data]] = []
        listFileName.forEach { fileName in
            if let image = task.getImg(fileName),let data = image.pngData(){
                var param: [String: Data] = [:]
                if !fileName.hasSuffix(".jpg") || !fileName.hasSuffix(".png"){
                    param.updateValue(data, forKey: "\(fileName).jpg")
                }else{
                    param.updateValue(data, forKey: fileName)
                }
                listData.append(param)
            }
        }
        if listFileName.count == 0{
            sucesss(listURL)
        }else{
            themeFileUpload(listData) { file in
                if let url = file.url{
                    if url.count == list.count{
                        var listMap: [String: String] = [:]
                        for (i,objc) in url.enumerated(){
                            listMap.updateValue(objc, forKey: list[i])
                        }
                        task.updateListFile(listMap)
                        
                        listMap.merge(listURL) { (current, _) in current }
                        sucesss(listMap)
                    }else{
                        failure("url is empty")
                    }
                }else{
                    failure("url is empty")
                }
            } failure: { error in
                failure(error)
            }

        }
    }
    
    
    
    private var userId: String?{
#if DEBUG
        return "2"
#else
        return UserInfoManager.sharedInstance.userId()
#endif
    }
}
fileprivate let taskManage = ThemeDiyManage()
extension ThemeDiyTask{

    func uploadThemeDiyData(_ item: ThemeDiy,
                    sucesss: @escaping ((_ info :ThemeDiy) -> ()),
                    failure: @escaping ((_ error  :String) -> ())){
        var listBg: [String] = []
        var listPreview: [String] = []
    
        var lockJSONConfig: String = ""
        var appJSONConfig: String = ""
        var widgetJSONConfig: String = ""
        let name = item.name ?? ""
        let tid = item.tid
        
        var listApp: [SCSubModel] = []
        var listLockModel: [LockWidgetModel] = []
        var listLockId: [String] = []
        if let data = item.lock_data,let model = taskManage.lockDataToLockModel(data){
            listApp = model.shareAppData.filter({$0.customPic.count > 0})
            listLockModel = model.listLockModel
            listLockModel.forEach { item in
                listLockId.append("\(item.type.rawValue)")
            }

            if let jsonString = String(data: data, encoding: .utf8){
                lockJSONConfig = jsonString
                debugPrint(jsonString)
            }
            if model.bg.count > 0{
                listBg.append(model.bg)
            }
            if model.bg_lock.count > 0 && model.bg_lock != model.bg{
                listBg.append(model.bg_lock)
            }
            if let imgs = item.img{
                listPreview.append(imgs)
            }
        }
        var listWidgetModel: [ModelProtocol] = []
        var listWidgetId: [String] = []
        if let data = item.panel_data{
            let list = taskManage.paneDataToPanelModel(data)
            list.forEach { objc in
                if objc.panelItem.panelName != "-1" || objc.panelItem.panelName != "-2"{
                    listWidgetModel.append(contentsOf: objc.listData)
                }
            }
            listWidgetModel.forEach { item in
                listWidgetId.append("\(item.type.rawValue)")
            }
        
            if let jsonString = String(data: data, encoding: .utf8){
                widgetJSONConfig = jsonString
            }
        }

        let group = DispatchGroup()
        //背景图片
        if listBg.count > 0{
            group.enter()
            uploadFile(listBg) { list in
                listBg = list
                group.leave()
            } failure: { error in
                listBg = []
                group.leave()
            }
        }
        //预览图
        if listPreview.count > 0{
            group.enter()
            uploadFile(listPreview) { list in
                listPreview = list
                group.leave()
            } failure: { error in
                listPreview = []
                group.leave()
            }
        }
        //app图片
        if listApp.count > 0{
            let listICON = listApp.map({ $0.customPic})
            group.enter()
            uploadFile(listICON) { list in
                var listAppData: [ThemeDiyApp] = []
                if listApp.count == list.count{
                    for (i,objc) in listApp.enumerated(){
                        let item = ThemeDiyApp(name: objc.name, url: list[i])
                        listAppData.append(item)
                    }
                    if let data = try? JSONEncoder().encode(listAppData){
                        if let jsonString = String(data: data, encoding: .utf8){
                            appJSONConfig = jsonString
                            debugPrint(jsonString)
                        }
                    }
                }
                group.leave()
            } failure: { error in
                listPreview = []
                group.leave()
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            themeUserDiyPost(name, tid: tid,
                                  widgets: listWidgetId,
                                  lockscreen_widgets: listLockId,
                                  previews_url: listBg,
                                  img_url: listPreview,
                             layout_configs: "",
                             app_configs: appJSONConfig,
                             lock_configs: lockJSONConfig,
                             widget_configs: widgetJSONConfig,
                             sucesss: sucesss,
                             failure: failure)
        }
    }
    
}
